package models

import (
	"fmt"
	"log"
	"os"
	"smc-admin/utils"
	"time"

	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

var DB *gorm.DB

type BaseModel struct {
	ID         int              `json:"id" gorm:"primaryKey;"`            //id
	CreateTime utils.TimeNormal `json:"createTime" gorm:"autoCreateTime"` //创建时间
	UpdateTime utils.TimeNormal `json:"updateTime" gorm:"autoUpdateTime"` //更新时间
	//DeleteTime gorm.DeletedAt `json:"deleteTime" gorm:"column:deleteTime;index"`
}

func InitDB() {
	conf := viper.GetStringMap("mysql")
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer（日志输出的目标，前缀和日志包含的内容——译者注）
		logger.Config{
			SlowThreshold:             time.Second,   // 慢 SQL 阈值
			LogLevel:                  logger.Silent, // 日志级别
			IgnoreRecordNotFoundError: true,          // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  false,         // 禁用彩色打印
		},
	)
	db, err := gorm.Open(mysql.Open(fmt.Sprintf("%v:%v@tcp(%v)/%v?charset=utf8mb4&parseTime=True&loc=Local", conf["name"], conf["pwd"], conf["tcp"], conf["db"])), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "",
			SingularTable: true,
		},
		Logger: newLogger,
	})
	if err != nil {
		panic("failed to connect database" + err.Error())
	}
	DB = db
	//user
	user := new(User)
	user.CreateTable()

	//types
	types := new(Types)
	types.CreateTable()

	//img
	img := new(Img)
	img.CreateTable()

	//video
	video := new(Video)
	video.CreateTable()

	//quality
	quality := new(Quality)
	quality.CreateTable()
}
